<?php
/**
 *
 */
class UsersController extends AppController {

	public $uses = array('Group', 'User');

	public $helpers = array('Html', 'Form');

	public function beforeFilter() {
		parent::beforeFilter();//Inherit
		if( !$this->Auth->loggedIn() )
		$this->Auth->allow('add'); // Letting users register themselves
	}

	public function isAuthorized($user) {
		// Users (students) can:
		if ( in_array($this->action, array('logout', 'profile', 'edit_profile', 'add_picture')) ) {
			return true;
		}

		// Show only to administrators
		if ( in_array($this->action, array('login', 'index', 'view', 'add', 'edit', 'delete', 'reset_password')) )
			if( $this->Auth->loggedIn() && $this->Auth->user('rights') !== 'admin' )
				return false;

		return parent::isAuthorized($user);
	}

	public function login() {
		$this->set('faculties', $this->User->Faculty->find('all'));
		if ($this->request->is('post')) {
			if ($this->Auth->login())
				$this->redirect($this->Auth->redirect());
			else
				$this->Session->setFlash(__('Invalid email or password, please try again'));
		}
	}
	
	/*
	 * When user logout (s)he redirected to default page of this action
	*/
	public function logout() {
		unset($_SESSION['dropbox_api']);
		$this->redirect($this->Auth->logout());
	}
	
	/**
	 * It creates a variable named users in which there are all'the users
	 */
	public function index() {
		$result = $this->User->query("SELECT User.* , Faculty.name AS faculty_name FROM users AS User LEFT JOIN faculties AS Faculty ON User.id_faculty = Faculty.id_faculty");
		$this->set('users', $result);
		$this->set('faculties', $this->User->Faculty->find('all'));
		$this->layout = 'admin';
	}


	/**
	 * Given an id, it returns the information about the user with that id
	 */
	public function profile($id = null) {
		if(is_null($id))
			$this->User->id = $this->Auth->user('id_user');//default
		else
			$this->User->id = $id;
		$this->set('users', $this->User->read());
	}

	/**
	 * Add a new user to the database
	 */
	public function add() {
		$faculties = $this->User->Faculty->find('all');
		$this->set('faculties', $faculties);
		$this->set('isAdmin', $this->Auth->loggedIn() && $this->Auth->user('rights') === 'admin');
		if ($this->request->is('post')) {
			//pr($this->request->data['User']);

			//Do not allow simple user registering like administrator
			if($this->Auth->user('rights') !== 'admin')
				unset($this->request->data['User']['rights']);

			if ($this->User->save($this->request->data)) {
				$this->Session->setFlash('User account has been created successfully.');
				$this->redirect(array('action' => 'index'));
			} else {
				$this->Session->setFlash('Unable to add new user.');
			}
		}
		if($this->Auth->user('rights') === 'admin')
			$this->layout = 'admin';
	}

	/**
	 * Edit the information about a user
	 */
	public function edit($id = null) {
		$this->User->id = $id;
		if ($this->request->is('get')) {
			$user_data = $this->User->read();
			unset($user_data['User']['password']);
			$this->request->data = $user_data;
		} else {
			if($this->Auth->user('rights') !== 'admin')
				unset($this->request->data['User']['rights']);
			if( empty($this->request->data['User']['password']) )
					unset($this->request->data['User']['password']);

			if ($this->User->save($this->request->data)) {
				//pr($this->request->data['rights']);
				$this->Session->setFlash('The user information have been updated.');
				$this->redirect(array('action' => 'index'));
			} else {
				$this->Session->setFlash('Unable to update the information.');
			}
		}
		$this->layout = 'admin';
	}

	/**
	 * Delete an user from the database
	 */
	public function delete($id = null) {
		if ($this->request->is('get')) {
			throw new MethodNotAllowedException();
		}
		if ($this->User->delete($id)) {
			$this->Session->setFlash('The user with id: ' . $id . ' has been deleted.');
			$this->redirect(array('action' => 'index'));
		}else{
			$this->redirect(array('action' => 'index'));
		}
		$this->layout = 'admin';
	}

	/**
	 * It creates a new password for the user
	 */
	public function reset_password($id = null) {
		$pwd = rand(100000, 999999);
		$this->User->read(null, $id);
		$this->User->set('password', $pwd);
		if ($this->User->save())
			$this->Session->setFlash('New password: ' + $pwd);
		else
			$this->Session->setFlash('Could not save the new password.');
		$this->redirect(array('action' => 'index'));
		$this->layout = 'admin';
	}
	
	
	/**
	 * Given the user's ID, it edits its profile
	 */
	public function edit_profile($id = null) {
		if( $this->Auth->loggedIn() && $this->Auth->user('rights') === 'admin' )
			$this->User->id = $id;
		// Students should not be allowed to edit others profile
		else
			$this->User->id = $this->Auth->user('id_user');

		if ($this->request->is('get')) {
			$user_data = $this->User->read();
			unset($user_data['User']['password']);
			$this->request->data = $user_data;
		} else {
			if( $this->Auth->loggedIn() && 
				($this->Auth->user('rights') === 'admin'
					|| $this->request->data['User']['id_user'] == $this->Auth->user('id_user') )
			) {
				if( empty($this->request->data['User']['password']) )
					unset($this->request->data['User']['password']);
				if ($this->User->save($this->request->data)) {
					$this->Session->setFlash('The profile informations have been updated.');
					$this->redirect(array('action' => 'profile', $this->User->id));
				} else {
					$this->Session->setFlash('Unable to update the information.');
				}
			} else 
				$this->Session->setFlash('You are not allowed to change other\'s profile.');
		}
	}
	
	
	
	function add_picture() {
		$id = $this->Auth->user('id_user');
		$this->User->id = $id;
		$this->set('id_user', $id);
		/*if($id == null){
			$this->Session->setFlash('id null');
		} else{*/
			
 		if (!empty($this->data) && is_uploaded_file($this->data['User']['File']['tmp_name'])) {
			// setup path to profile pictures directory
			$profile_img_path = 'img/profile';
			// create the folder if it does not exist
			if(!is_dir($profile_img_path))
				mkdir($profile_img_path);
			
			$file = $this->data['User']['File'];
	 		// loop through and deal with the files 
			// replace spaces with underscores
			$filename = str_replace(' ', '_', $file['name']); 
			// assume file type is OK
			$typeOK = true;

			// if file type ok upload the file
			if($typeOK) {
				// switch based on error code
				switch($file['error']) {
					case 0:
						// check filename already exists
						if(!file_exists($profile_img_path.'/'.$filename)) {
							// create full filename
							$full_url = $profile_img_path.'/'.$filename;
							$url = $profile_img_path.'/'.$filename;
							// upload the file
							$success = move_uploaded_file($file['tmp_name'], $url);
					 	} else {
							// create unique filename and upload file
							ini_set('date.timezone', 'Europe/London');
							$now = date('Y-m-d-His');
							$full_url = $profile_img_path.'/'.$now.$filename;
							$url = $profile_img_path.'/'.$now.$filename;
							$success = move_uploaded_file($file['tmp_name'], $url);
						}
						// if upload was successful
						if($success) {
							// save the url of the file
							$result['urls'][] = $url;
							$this->request->data['User']['id_user'] = $id;
							$this->request->data['User']['photo'] = $this->data['User']['File']['name'];
							//pr($this->request->data['User']['photo']);
	
							/*if ($this->User->save($this->request->data)) {
								$this->redirect(array('action' => 'profile', $this->User->id));
							} else {
							$result['errors'][] = "Error uploading $filename. Please try again.";
													$this->Session->setFlash($filename.' File not uploaded'); 
							}*/
	
							$this->User->query("UPDATE users SET photo='".addslashes($this->data['User']['File']['name'])."' WHERE id_user=".$id);
							$this->redirect(array('action' => 'profile', $this->User->id));
						}
					break;
					case 3:
						// an error occurred
						$result['errors'][] = "Error uploading $filename. Please try again.";
						$this->Session->setFlash('Error uploading '.$filename.'. Please try again.'); 
					break;
					default:
						// an error occurred
						$result['errors'][] = "System error uploading $filename. Contact with web administrator."; 
						$this->Session->setFlash('Error uploading '.$filename.'. Please try again.');
					break;
				}
			} elseif($file['error'] == 4) {
				// no file was selected for upload
				$result['nofiles'][] = "No file Selected";
			} else {
				// unacceptable file type
				$result['errors'][] = "$filename cannot be uploaded. Acceptable file types: gif, jpg, png."; 
				$this->Session->setFlash($filename.' cannot be uploaded. Acceptable file types: gif, jpg, png.');
			}
		}
		//}
	}
}
